package com.gigi.searchcenterbackendmaster.datasource;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.gigi.searchcenterbackendmaster.exception.BusinessException;
import com.gigi.searchcenterbackendmaster.model.enums.ErrorCodeEnum;
import com.gigi.searchcenterbackendmaster.model.vo.PictureVO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 图片数据源
 *
 * @author Gigi
 * @date 2024/8/17 17:17
 */
@Component
public class PictureDataSource implements DataSource<PictureVO> {

    @Override
    public List<PictureVO> doSearch(String keyword) {
        String url = StrUtil.format("https://cn.bing.com/images/search?q={}&first=1", keyword);
        Document doc = null;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCodeEnum.SYSTEM_ERROR, "图片数据获取异常");
        }
        Elements elements = doc.select(".iuscp");
        if (elements.isEmpty()) {
            return Collections.emptyList();
        }
        return elements.stream().map(e -> {
            PictureVO picture = new PictureVO();
            String m = e.select(".iusc").get(0).attr("m");
            Map<String, Object> map = JSONUtil.toBean(m, Map.class);
            String murl = (String) map.get("murl");
            picture.setUrl(murl);
            String title = e.select(".inflnk").get(0).attr("aria-label");
            picture.setTitle(title);
            return picture;
        }).collect(Collectors.toList());
    }

}
